<template>
    <div>
        <div class="">
            <el-button @click="start" type="primary">查询</el-button>
            <el-button @click="add" type="primary">新增</el-button>
        </div>
        <el-table v-loading="loading" class="margin-top20" ref="multipleTable" border :data="tableData" height="74vh"
            style="width: 100%">
            <el-table-column prop="ID" label="ID" width="60"> </el-table-column>
            <el-table-column prop="name" label="名称" width="150"> </el-table-column>
            <el-table-column prop="group" label="group"> </el-table-column>
            <el-table-column prop="model" label="model"> </el-table-column>
            <el-table-column prop="system" label="system" show-overflow-tooltip> </el-table-column>
            <el-table-column prop="prompt" label="prompt" show-overflow-tooltip> </el-table-column>
            <el-table-column prop="schema" label="schema" show-overflow-tooltip> </el-table-column>
            <el-table-column prop="modelsId" label="modelsId" width="" :show-overflow-tooltip="{ effect: 'light' }"
                :tooltip-formatter="withVNode">
                <template #default="{ row }">
                    <el-tag class="question-label" v-for="(v, k) in row?.modelsId" :key="k">
                        {{models.find(e => e.ID === v)?.name}}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="temperature" label="temperature" width="120"> </el-table-column>
            <el-table-column prop="" label="操作" width="210">
                <template #default="{ row }">
                    <el-button-group>
                        <el-button type="success" @click="update(row)">查看</el-button>
                        <el-button type="danger" @click="del(row?.ID)">删除</el-button>
                        <el-button type="primary" @click="update(row)">修改 </el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination class="pager" :page-size="limit" :total="totalCount" @current-change="changePage"
            layout="total,prev, pager, next" :current-page="Math.floor(offset / limit) + 1">
        </el-pagination>
        <!--  -->
        <el-dialog v-model="dialogVisible" width="60%" @close="close" align-center>
            <template #header>
                <span class="icon-text el-dialog__header-title">
                    <el-icon class="text-primary">
                        <Guide />
                    </el-icon>
                    {{ isUpdate ? '修改' : '新增' }}提示词
                </span>
            </template>
            <el-form ref="formDataRef" :model="formData" :rules="rules" status-icon label-width="100"
                class="demo-formData">
                <el-form-item label="名称" prop="name">
                    <el-input v-model.trim="formData.name" />
                </el-form-item>
                <el-form-item label="group" prop="group">
                    <el-input v-model.trim="formData.group" />
                </el-form-item>
                <el-form-item label="model" prop="model">
                    <el-input v-model.trim="formData.model" />
                </el-form-item>
                <el-form-item label="system" prop="system">
                    <el-input v-model="formData.system" type="textarea" :autosize="{ minRows: 4, }" />
                </el-form-item>
                <el-form-item label="prompt" prop="prompt">
                    <el-input v-model="formData.prompt" type="textarea" :autosize="{ minRows: 8, }" />
                </el-form-item>
                <el-form-item label="schema" prop="schema">
                    <el-input v-model="formData.schema" type="textarea" :autosize="{ minRows: 4, }" />
                </el-form-item>
                <el-form-item label="模型" prop="modelsId">
                    <el-select v-model="formData.modelsId" multiple placeholder="请选择模型" style="" value-key="ID">
                        <template #label="{ label, value }">
                            <span>{{ label }}: </span>
                            <span style="font-weight: bold">{{models.find(e => e.ID === value)?.description}}</span>
                        </template>
                        <el-option v-for="item in models" :key="item.ID" :label="item.name" :value="item?.ID">
                            <div style="display: flex; flex-direction: row;">
                                <div style="font-weight: bold">{{ item.name }}</div>
                                <div style="color: #888;  margin-left: 10px;">{{ item.description }} </div>
                            </div>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="temperature" prop="temperature">
                    <el-input-number v-model="formData.temperature" :max="2" :min="0" :step="0.1" />
                </el-form-item>

            </el-form>
            <template #footer>
                <el-button type="primary" size="default" @click="submit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox, ElTag, FormInstance, FormRules, TableTooltipData } from "element-plus";
import { computed, h, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { asyncCreateorupdatechatprompt, asyncDelchatprompt, asyncSelectchatprompt, asyncSelectmodel } from "../../../api";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";

const router = useRouter()
const route = useRoute()
const store = useStore(Storekey)

onMounted(() => { start() })

const loading = ref(false)
// 查询条件
const offset = ref<number>(0)
const limit = ref<number>(20)
const totalCount = ref<number>(0)
const tableData = ref<Studycodemodel.Ichatprompt[]>([])
const models = ref<Studycodemodel.Ichatmodel[]>([])
async function start() {
    try {
        loading.value = true
        const { rows, count } = await asyncSelectchatprompt({
            _offset: offset.value,
            _limit: limit.value,
            _sortable: "DESC"
        })
        loading.value = false
        totalCount.value = count
        tableData.value = rows

        const ret = await asyncSelectmodel()
        models.value = ret.rows
    } catch (error) {
        console.error(error)
    }
}
function changePage(r: number) {
    offset.value = (r - 1) * limit.value
    start()
}

async function del(ID: number) {
    try {
        ElMessageBox.confirm(`确定删除此提示词?`, '提示', {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(async e => {
            await asyncDelchatprompt({ ID })
            start()
            ElMessage.success("操作成功")
        }).catch(f => {
            ElMessage.error(f)
        })

    } catch (error) {
        console.error(error)
    }
}

const dialogVisible = ref(false)
function close() {
    formDataRef.value?.clearValidate()
}
const formDataRef = ref<FormInstance>()
const formData = ref<Studycodemodel.Ichatprompt>({})
const isUpdate = computed(() => {
    return formData.value?.ID
})
const rules = reactive<FormRules<typeof formData>>({
    name: [{ required: true, message: '名称为必填', trigger: 'blur', },],
    model: [{ required: true, message: 'model为必填', trigger: 'blur', },],
    system: [{ required: true, message: 'system为必填', trigger: 'blur', },],
    prompt: [{ required: true, message: 'prompt为必填', trigger: 'blur', },],
})
async function submit() {
    // 校验表单
    formDataRef.value?.validate(async (valid) => {
        if (valid) {
            try {
                const dataToSubmit = {
                    ...formData.value,
                    schema: formData.value?.schema?.trim() === '' ? null : formData.value?.schema
                }
                await asyncCreateorupdatechatprompt(dataToSubmit)
                start()
                ElMessage.success("操作成功")
                dialogVisible.value = false
            } catch (error) {
                console.error(error)
            }
        }
        else {
            console.log("表单验证失败=>", formData.value)
        }
    })
}

function add() {
    dialogVisible.value = true
    formData.value = {}
}

async function update(row: Studycodemodel.Ichatprompt) {
    dialogVisible.value = true
    formData.value = row
}

const withVNode = (data: TableTooltipData<Studycodemodel.Ichatprompt>) => {
    if (!models.value || !Array.isArray(data.cellValue)) return "未知";

    return h("div", {},
        data.cellValue.map((v, k) =>
            h(ElTag, { class: "question-label", key: k, type: "primary", effect: "light" }, () => {
                return models.value.find(e => e.ID === v)?.name || "未知"
            })
        )
    );
};


</script>

<style scoped>
.router-link-active {
    color: cadetblue;
}
</style>